package com.websocket.service.Impl;

import com.websocket.dto.WechatDTO;
import com.websocket.repository.mongo.OtoWechatRepository;
import com.websocket.service.OtoWechatService;
import com.websocket.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Created by yhn on 2018/6/15.
 */
@Service
public class OtoWechatServiceImpl implements OtoWechatService {
    @Autowired
    private OtoWechatRepository otoWechatRepository;
    @Override
    public List<WechatDTO> findByToUseridAndFlag(String userid, int flag) {
        return otoWechatRepository.findByToUseridAndFlag(userid,flag);
    }

    @Override
    public PageVO<WechatDTO> findByUseridAndToUserid(String userid, String toUserid,String toUserid2,String userid2, Pageable pageable) {
        System.out.println("userid:"+userid+"，toUserid:"+toUserid);
      //  Sort sort = new Sort(Sort.Direction.DESC,"create_time");   //降序----根据创建时间来进行降序
        PageRequest request =  PageRequest.of(pageable.getPageNumber(),pageable.getPageSize(),pageable.getSort());
        Page<WechatDTO> wechatPage = otoWechatRepository.findByUseridAndToUseridOrUseridAndToUserid(userid,toUserid,toUserid,userid,request);
        System.out.println("wechatPage:"+wechatPage);
        PageVO pageVO = new PageVO();
        pageVO.setCurrentPage(pageable.getPageNumber());
        pageVO.setSize(pageable.getPageSize());
        pageVO.setTotalPage(wechatPage.getTotalPages());
        List<WechatDTO> list = new ArrayList<>();
        for (WechatDTO wechatDTO : wechatPage.getContent()) {
            list.add(wechatDTO);
        }
        Collections.reverse(list);    //实现list集合逆序排列
        pageVO.setDataList(list);
        pageVO.setFlag(2);   //未枚举  类型-->单聊记录

        List<WechatDTO> wechatDTOList = otoWechatRepository.findByUseridAndToUseridAndFlag(toUserid,userid,1);
        for (WechatDTO wechatDTO : wechatDTOList) {
            wechatDTO.setFlag(0);
        }
        otoWechatRepository.saveAll(wechatDTOList);

        return pageVO;
    }

    @Override
    public WechatDTO userGetMsg(String _id) {
      WechatDTO wechatDTO = otoWechatRepository.findBy_id(_id);
      wechatDTO.setFlag(0);
      return otoWechatRepository.save(wechatDTO);
    }
}
